<?php


class FieldsCheck {
  public function __construct(){
  }
  
  public function check(array $data, array $checks) {
    $errors = array();
    foreach($checks as $check) {
      $info = is_array(@$data[$check[0]])?@$data[$check[0]][0]:@$data[$check[0]];
      if(!$this->checkValue($info, $check[1], $check[2])){
        $errors[$check[0]] = $check[3];
      }
    }
    return $errors;
  }

  private function checkValue($value, $type, $mandatory) {
    switch($type) {
      case 'int':
        return $this->int((int)$value, $mandatory);
        break;
      case 'int_positive':
        return $this->int((int)$value, $mandatory) && $this->positive($value);
        break;
      case 'float':
        return $this->float((float)$value, $mandatory);
        break;
      case 'float_positive':
        return $this->float((float)$value, $mandatory) && $this->positive($value);
        break;
        case 'url':
        return $this->url($value, $mandatory);
        default:
      case 'email':
        return $this->email($value, $mandatory);
        default:
      case 'string':
        return $this->string($value, $mandatory);
        break;
      default:
        return true;
        break;
    }
  }
  
  private function string($arg, $mandatory=true) {
    if($mandatory && empty($arg)) {
      return false;
    }
    return true;
  }
  
  private function int($arg, $mandatory=true) {
    if($mandatory && empty($arg)) {
      return false;
    }
    if(is_int($arg)){
      return true;
    }
    return false;    
  }
  private function float($arg, $mandatory=true) {
    if($mandatory && empty($arg)) {
      return false;
    }
    if(is_float($arg)){
      return true;
    }
    return false;    
  }
  
  private function email($arg, $mandatory=true) {
    if($mandatory && empty($arg)) {
      return false;
    } else if(empty($arg) && !$mandatory) {
      return true;
    }
    return preg_match("/^[\w-]+(?:\.[\w-]+)*@(?:[\w-]+\.)+[a-zA-Z]{2,7}$/", $arg);
  }
  
  private function url($arg, $mandatory=true) {
    if($mandatory && empty($arg)) {
      return false;
    }
    return preg_match("/^(http|https|ftp):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?(\/)?/i", $value);
  }
  
  private function positive($arg) {
    return $arg>=0;
  }

  private function negative($arg) {
    return $arg<0;
  }
  
}
?>